﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace HireMyStuffSilverlight.helpers
{
    public static class FragmentParsingHelper
    {
        private const string ValueDelimiter = "=";
        private const string StatePairDelimiter = "&";

        /// <summary>
        /// Parses the fragment string into name/value pairs
        /// </summary>
        /// <param name="uri">The Uri to parse the query string from</param>
        /// <returns>A dictionary containing one entry for each name/value pair in the query string</returns>
        public static IDictionary<string, string> ParseFragmentToDictionary(string fragment)
        {
            IDictionary<string, string> dict = new Dictionary<string, string>(StringComparer.Ordinal);

            string[] kvps = fragment.Split(StatePairDelimiter.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            foreach (string kvp in kvps)
            {
                int delimiterIndex = kvp.IndexOf(ValueDelimiter, StringComparison.Ordinal);
                if (delimiterIndex == -1)
                {
                    dict.Add(
                        HttpUtility.UrlDecode(kvp),
                        String.Empty);
                }
                else
                {
                    dict.Add(
                        HttpUtility.UrlDecode(kvp.Substring(0, delimiterIndex)),
                        HttpUtility.UrlDecode(kvp.Substring(delimiterIndex + 1)));
                }
            }

            return dict;
        }

        public static string ConvertToString(IDictionary<string, string> dictionary)
        {
            StringBuilder sb = new StringBuilder(200);

            if (dictionary.Count > 0)
            {
                foreach (string key in dictionary.Keys)
                {
                    sb = sb.AppendFormat(CultureInfo.InvariantCulture,
                                         "{0}{1}{2}{3}",
                                         key,
                                         ValueDelimiter[0],
                                         dictionary[key],
                                         StatePairDelimiter[0]);
                }

                // Strip off the last delimiter between internal state pairs
                sb = sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }
    }
}
